package MyBloomFilter;

import MyBitSet.MyBiterSet;

/**
 * Description:
 * User:岁亮亮
 * Date:2025-03-19
 * TIME:11:30
 */

class SimpleHash{

    public int capacity;
    public int seed;

    public SimpleHash(int capacity,int seed){
        this.capacity = capacity;
        this.seed = seed;
    }
    public final int hash(String val){
        int h = 0;

        return (val == null) ? 0 : (capacity-1) & (seed * (h = val.hashCode()) ^ (h >>> 16));

    }
}
public class MyBloomFilter {
    public MyBiterSet myBiterSet;

    public int usedSize;
    public final int[] seed = {22,32,14,16};

    public static final int DEAFAULt_CAPACITY = 1 << 20;


    public SimpleHash[] simpleHashes;

    public MyBloomFilter(){
        myBiterSet = new MyBiterSet(DEAFAULt_CAPACITY);
        this.simpleHashes = new SimpleHash[seed.length];
        for(int i = 0; i < seed.length; i++){
            simpleHashes[i] = new SimpleHash(DEAFAULt_CAPACITY,seed[i]);
        }
    }
    public MyBloomFilter(int capacity){
        myBiterSet = new MyBiterSet(capacity);
        this.simpleHashes = new SimpleHash[seed.length];
        for(int i = 0; i < seed.length; i++){
            simpleHashes[i] = new SimpleHash(capacity,seed[i]);
        }
    }

    /**
     * 插入数据
     * 1.经过多次哈希
     * 2 得到位图多个位置,并置为1;
     * 3.
     * @param val
     */
    public void add(String val) {

        for(SimpleHash simpleHash : simpleHashes){
            int index = simpleHash.hash(val);
            myBiterSet.set(index);
        }
        usedSize++;

    }

    public boolean contains(String val){
        boolean flag = true;

        for(SimpleHash simpleHash : simpleHashes){
            int index = simpleHash.hash(val);
            flag = myBiterSet.get(index);
            if(!flag)break;
        }

        return flag;
    }

    public static void main(String[] args) {
        MyBloomFilter myBloomFilter = new MyBloomFilter();
        myBloomFilter.add("hello");
        myBloomFilter.add("hello2");
        myBloomFilter.add("bite");
        myBloomFilter.add("bite2");
        System.out.println(myBloomFilter.contains("hello211"));
    }

}
